package main

import (
	"flag"
	//"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"gopkg.in/yaml.v2"

	"github.com/yangyongzhen/mqtt-broker/internal/auth"
	"github.com/yangyongzhen/mqtt-broker/internal/broker"
)

func main() {
	var (
		debug = flag.Bool("debug", false, "Enable debug logging")
		conf  = flag.String("f", "etc/config.yaml", "the config file")
	)
	flag.Parse()

	if *debug {
		log.SetFlags(log.LstdFlags | log.Lshortfile)
	}

	// 读取配置文件
	yamlFile, err := os.ReadFile(*conf)
	if err != nil {
		log.Fatalf("读取配置文件失败: %v", err)
	}

	// 解析配置文件
	var config broker.Config
	err = yaml.Unmarshal(yamlFile, &config)
	if err != nil {
		log.Fatalf("解析配置文件失败: %v", err)
	}

	// 使用配置
	log.Printf("监听端口: %d", config.Server.Port)
	log.Printf("最大连接数: %d", config.Server.MaxConnections)
	log.Printf("最大消息大小: %d", config.Server.MaxMessageSize)
	log.Printf("存储类型: %s", config.Storage.Type)

	// 创建认证器
	authenticator := auth.NewSimpleAuthenticator()

	// 添加一些测试用户
	authenticator.AddUser("admin", "password")
	authenticator.AddUser("test", "test123")

	// 创建broker
	mqttBroker, err := broker.NewBroker(&config, authenticator)
	if err != nil {
		log.Fatalf("创建broker失败: %v", err)
	}
	// 处理信号
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		sig := <-sigChan
		log.Printf("Received signal %v, shutting down broker...\n", sig)
		mqttBroker.Stop()
		os.Exit(0)
	}()

	// 启动broker
	if err := mqttBroker.Start(); err != nil {
		log.Fatalf("Failed to start broker: %v", err)
	}
}
